package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.BeanCopyUtils;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.SystemConstants.LOGIN_CODE;
import static com.hmdp.utils.SystemConstants.LOGIN_USER;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        if (!RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("电话号码格式错误");
        }//电话号码格式正确，生成验证码
        String code = RandomUtil.randomNumbers(6);
        //保存验证码至session
        //session.setAttribute(phone,code);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE+phone,code,2, TimeUnit.MINUTES);
        //发送验证码
        log.debug("发送验证码成功，验证码: {}",code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //校验手机号
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
//        Object sessionCode = session.getAttribute(phone);
        String sessionCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE + phone);
        if (!RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("电话号码格式错误");
        }
        //校验验证码
        if (sessionCode==null || !sessionCode.equals(code)){
            //不一致，报错
            return Result.fail("验证码错误！");
        }
        //一致，根据手机号查询用户
        User user = lambdaQuery().eq(User::getPhone, phone).one();
        //判断用户是否存在
        if (user==null){
            user=new User();
            //不存在，创建用户
            user.setPhone(phone);
            String nickName = "user_"+RandomUtil.randomString(10);
            user.setNickName(nickName);
            save(user);
        }
        //保存用户信息到session中
//        session.setAttribute(key,user);
        //保存用户信息到redis中 key-hash结构，需要对用户进行转化
        //1.设置登录令牌token作为key保存数据
        String token = UUID.randomUUID().toString();
        System.out.println("token:"+token);
        //2.将user转化为hashmap
        UserDTO userDTO = BeanCopyUtils.copyOne(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString()));
        //3.存入数据
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER+token,userMap);
        stringRedisTemplate.expire(LOGIN_USER+token,24,TimeUnit.HOURS);
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //1.获取用户id
        Long userId = UserHolder.getUser().getId();
        //2.获取当前年月日,组装成key
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();
        //拼装成key
        String key = SystemConstants.USER_SIGN + userId + keySuffix;
        //3.对Redis操作
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //1.获取用户和年月日
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();
        //2.拼接key，并且查询0到当天的签到量 BITFIELD sign:1010:202309 GET u24 0
        String key = SystemConstants.USER_SIGN + userId + keySuffix;
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (result == null || result.isEmpty()){
            return Result.ok(0);
        }
        Long num = result.get(0);
        if (num == null || num == 0){
            return Result.ok(0);
        }
        int count = 0;
        //3.右移运算和与运算获取当前位，是1就加一，是0就返回
        while (true){
            //相与获取当前位的数 1&1=1 1&0=0
            if ((num & 1) == 0) {
                break;
            }else {
                count++;
            }
            //执行右移操作，使其循环向右读取
            num >>>= 1;
        }
        return Result.ok(count);

    }
}











